package cn.eeepay.framework.service.impl.aatAgentActivity;

import cn.eeepay.framework.dao.aatAgentActivity.AgentActivityDao;
import cn.eeepay.framework.db.pagination.Page;
import cn.eeepay.framework.model.UserLoginInfo;
import cn.eeepay.framework.model.aatAgentActivity.*;
import cn.eeepay.framework.service.SysDictService;
import cn.eeepay.framework.service.aatAgentActivity.AgentActivityService;
import cn.eeepay.framework.service.impl.SeqService;
import cn.eeepay.framework.util.ExportResult;
import cn.eeepay.framework.util.ListDataExcelExport;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("agentActivityService")
public class AgentActivityServiceImpl implements AgentActivityService {

    private static final Logger log = LoggerFactory.getLogger(AgentActivityServiceImpl.class);

    @Resource
    private AgentActivityDao agentActivityDao;

    @Resource
    private SeqService seqService;

    @Resource
    private SysDictService sysDictService;

    /**
     * 查询活动列表
     * @param info
     * @param page
     * @return
     */
    @Override
    public List<AgentActivity> selectAllList(AgentActivity info, Page<AgentActivity> page) {
        return  agentActivityDao.selectAllList(info,page);
    }

    /**
     * 修改活动状态
     * @param id
     * @param sta
     * @return
     */
    @Override
    public int saveSwitch(int id, String sta) {
        return agentActivityDao.saveSwitch(id,sta);
    }

    /**
     * 新增代理商活动
     * @param info
     * @param msg
     * @return
     */
    @Override
    public int addAgentActivity(AgentActivity info, Map<String, Object> msg) {
        // 获取当前登录的人
        UserLoginInfo principal = (UserLoginInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        info.setOperator(principal.getUsername());
        
        info.setActCode("AT"+seqService.createKey("aat_agent_activity", "%05d"));
        //生成活动链接
        //agentApi2_url
        //http://cs-ys-agentapi2.51ydmw.com/agentApi2/static/zhounianqing/index.html#/?actCode=AT00002
        info.setActLink(sysDictService.getValueByKey("agentApi2_url_extranet")+"/static/zhounianqing/index.html#/?actCode="+info.getActCode());
        int num=agentActivityDao.addAgentActivity(info);
        if(num>0){
            //默认生成2条基础数据
            if(info.getDetailList()!=null&&info.getDetailList().size()>0){
                for(AgentActivityDetail item:info.getDetailList()){
                    //更新少量数据
                    item.setActCode(info.getActCode());
                    item.setOperator(principal.getUsername());
                    item.setActDetCode("AD"+seqService.createKey("aat_agent_activity_detail", "%05d"));
                    agentActivityDao.insertDetailLittle(item);
                }
            }
            msg.put("actCode",info.getActCode());//返回前端加载数据
            msg.put("msg","新增成功");
            msg.put("status", true);
        }else{
            msg.put("msg","新增失败");
            msg.put("status", false);
        }
        return num;
    }

    /**
     * 获取活动基础数据
     * @param actCode
     * @return
     */
    @Override
    public AgentActivity getAgentActivity(String actCode) {
        AgentActivity info=agentActivityDao.getAgentActivity(actCode);
        if(info!=null){
            info.setDetailList(agentActivityDao.getDetailList(info.getActCode()));
        }
        return info;
    }

    /**
     * 修改活动基础数据
     * @param info
     * @param msg
     * @return
     */
    @Override
    public int editAgentActivity(AgentActivity info, Map<String, Object> msg) {
        int num=agentActivityDao.editAgentActivity(info);
        if(num>0){
            if(info.getDetailList()!=null&&info.getDetailList().size()>0){
                for(AgentActivityDetail item:info.getDetailList()){
                    //修改时候只更新子活动状态
                    agentActivityDao.updateDetailStatus(item);
                }
            }
            msg.put("msg","修改成功");
            msg.put("status", true);
        }else{
            msg.put("msg","修改失败");
            msg.put("status", false);
        }
        return num;
    }

    /**
     * 删除活动
     * @param actCode
     * @param msg
     * @return
     */
    @Override
    public int deleteAgentActivity(String actCode, Map<String, Object> msg) {
        AgentActivity oldInfo=agentActivityDao.getAgentActivity(actCode);
        if(oldInfo.getOpenStatus().intValue()==1){
            msg.put("msg","开关状态不符合,不能删除");
            msg.put("status", false);
            return 0;
        }
        int num=agentActivityDao.deleteAgentActivityByCode(actCode);
        if(num>0){
            agentActivityDao.deleteAgentActivityDetailByCode(actCode);
            agentActivityDao.deleteRewardConfigByCode(actCode);
            msg.put("msg","删除成功");
            msg.put("status", true);
        }else{
            msg.put("msg","删除失败");
            msg.put("status", false);
        }
        return num;
    }

    /**
     * 获取子活动数据
     * @param actDetCode
     * @return
     */
    @Override
    public AgentActivityDetail getAgentActivityDetail(String actDetCode) {
        AgentActivityDetail info=agentActivityDao.getAgentActivityDetail(actDetCode);
        if(info!=null){
            //json转换map
            if(StringUtils.isNotBlank(info.getActiveExt())){
                info.setActiveExtMap((Map<String,Object>) JSON.parse(info.getActiveExt()));
            }
            info.setRewardList(agentActivityDao.getAgentActRewardConfigList(info.getActDetCode()));
        }
        return info;
    }

    @Override
    public int editAgentActivityDetail(AgentActivityDetail info, Map<String, Object> msg) {
        //将map转换成JSON
        if(info.getActiveExtMap()!=null){
            info.setActiveExt(JSON.toJSONString(info.getActiveExtMap()));
        }
        int num=agentActivityDao.editAgentActivityDetail(info);
        if(num>0){
            List<AgentActRewardConfig> list=info.getRewardList();
            List<AgentActRewardConfig> oldList=agentActivityDao.getAgentActRewardConfigList(info.getActDetCode());
            String strs=handleList(oldList);
            if(list!=null&&list.size()>0){
                for(AgentActRewardConfig item:list){
                    if(item.getId()==null){
                        //新增
                        item.setRewardCode("RW"+seqService.createKey("aat_agent_act_reward_config", "%05d"));
                        item.setActCode(info.getActCode());
                        item.setActDetCode(info.getActDetCode());
                        agentActivityDao.addRewardConfig(item);
                    }else{
                        strs=handleString(strs,item.getId().toString());
                        //修改
                        agentActivityDao.updateRewardConfig(item);
                    }
                }
            }
            //清除删除过的数据
            if(strs!=null&&!",".equals(strs)){
                strs= strs.substring(1,strs.length()-1);
                agentActivityDao.deleteRewardConfig(strs);
            }
            msg.put("msg","保存成功");
            msg.put("status", true);
        }else{
            msg.put("msg","保存失败");
            msg.put("status", false);
        }
        return num;
    }

    private String handleList(List<AgentActRewardConfig> list){
        StringBuffer sb=new StringBuffer();
        sb.append(",");
        if(list!=null&&list.size()>0){
            for(AgentActRewardConfig item:list){
                sb.append(item.getId()+",");
            }
        }
        return sb.toString();
    }
    /**
     * @param strs ,1,2,3,4,5
     * @param oldStr 4
     */
    private String handleString(String strs,String oldStr){
        String str=","+oldStr+",";
        if(strs.indexOf(str)>-1){
            return strs.replace(str,",");
        }
        return strs;
    }


    /**
     * 查询活动数据列表
     * @param info
     * @param page
     * @return
     */
    @Override
    public List<AgentActivityData> selectAgentActivityData(AgentActivityData info, Page<AgentActivityData> page) {
        //查询配置值
        Map<String,AgentActivityDetail> map=getConfig(info.getActCode());
        //如果没有匹配
        AgentActivityDetail config="2".equals(info.getActType())?map.get("config2"):map.get("config1");
        List<AgentActivityData> list=agentActivityDao.selectAgentActivityData(info,page,config);
        return list;
    }

    /**
     * 获取配置值
     * @param actCode
     * @return
     */
    private Map<String,AgentActivityDetail> getConfig(String actCode){
        Map<String,AgentActivityDetail> map=new HashMap<String,AgentActivityDetail>();
        List<AgentActivityDetail> configList=agentActivityDao.getDetailList(actCode);
        if(configList!=null&& configList.size()>0){
            for(AgentActivityDetail item:configList){
                //json转换map
                if(StringUtils.isNotBlank(item.getActiveExt())){
                    item.setActiveExtMap((Map<String,Object>) JSON.parse(item.getActiveExt()));
                }
                //配置了数据,才可以计算牛气值，豪气值这些
                if("1".equals(item.getActType())){
                    map.put("config1",item);//百团
                }else if("2".equals(item.getActType())){
                    map.put("config2",item);//千团
                }
            }
        }
        return map;
    }

    @Override
    public void exportActivityData(AgentActivityData info, HttpServletResponse response) throws Exception{
        //查询配置值
        Map<String,AgentActivityDetail> map=getConfig(info.getActCode());
        AgentActivityDetail config="2".equals(info.getActType())?map.get("config2"):map.get("config1");
        List<AgentActivityData> list = agentActivityDao.exportActivityDataSelect(info,config);


        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        OutputStream ouputStream = null;
        String fileName = null;
        if("2".equals(info.getActType())){
            fileName = "千团大战活动数据" + sdf.format(new Date()) + ".xls";
        }else{
            fileName = "百团大战活动数据" + sdf.format(new Date()) + ".xls";
        }
        String fileNameFormat = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        response.setHeader("Content-disposition", "attachment;filename=" + fileNameFormat);
        List<Map<String, String>> data = new ArrayList<Map<String, String>>();

        if(list.size()<1){
            Map<String, String> maps = new HashMap<String, String>();
            maps.put("rankSeq", null);
            maps.put("actName",null);
            maps.put("agentNo",null);
            maps.put("agentName",null);
            maps.put("agentLevel",null);
            maps.put("agentNode",null);
            maps.put("oneAgentNo",null);
            maps.put("oneAgentName",null);
            maps.put("oneSaleName",null);
            maps.put("totalMersStr", null);
            maps.put("totalTransStr", null);
            maps.put("totalActMersStr",null);
            maps.put("totalAverageTrans",null);
            maps.put("totalActTransStr",null);
            maps.put("totalNoActMers",null);
            maps.put("totalAverageNoActTrans",null);
            maps.put("score",null);
            if("2".equals(info.getActType())){
                maps.put("joinRatio",null);
            }
            data.add(maps);
        }else{
            for (AgentActivityData item : list) {
                Map<String, String> maps = new HashMap<>();
                maps.put("rankSeq", item.getRankSeq()==null?null:item.getRankSeq().toString());
                maps.put("agentNo", item.getAgentNo());
                maps.put("agentName", item.getAgentName());
                maps.put("agentLevel", item.getAgentLevel());
                maps.put("agentNode", item.getAgentNode());
                maps.put("oneAgentNo", item.getOneAgentNo());
                maps.put("oneAgentName", item.getOneAgentName());
                maps.put("oneSaleName", item.getOneSaleName());
                maps.put("totalMersStr", item.getTotalMersStr()==null?null:item.getTotalMersStr().toString());
                maps.put("totalTransStr", item.getTotalTransStr()==null?null:item.getTotalTransStr().toString());
                maps.put("totalActMersStr", item.getTotalActMersStr()==null?null:item.getTotalActMersStr().toString());
                maps.put("totalAverageTrans", item.getTotalAverageTrans()==null?null:item.getTotalAverageTrans().toString());
                maps.put("totalActTransStr", item.getTotalActTransStr()==null?null:item.getTotalActTransStr().toString());
                maps.put("totalNoActMers", item.getTotalNoActMers()==null?null:item.getTotalNoActMers().toString());
                maps.put("totalAverageNoActTrans", item.getTotalAverageNoActTrans()==null?null:item.getTotalAverageNoActTrans().toString());
                maps.put("score", item.getScore()==null?null:item.getScore().toString());
                if("2".equals(info.getActType())){
                    maps.put("joinRatio", item.getJoinRatio());
                }
                data.add(maps);
            }
        }
        ListDataExcelExport export = new ListDataExcelExport();
        String[] cols=null;
        String[] colsName=null;
        if("2".equals(info.getActType())){//千团
            cols = new String[]{"agentNo", "agentName", "agentLevel", "agentNode","oneAgentNo", "oneAgentName", "oneSaleName","totalMersStr","totalTransStr",
                    "totalActMersStr", "totalAverageTrans", "totalActTransStr", "totalNoActMers", "totalAverageNoActTrans", "score","joinRatio"};
            colsName = new String[]{"代理商编号","代理商名称","代理商级别","代理商节点","一级代理商编号","一级代理商名称","一级代理商所属销售","交易商户数","累计商户交易额",
                    "累计活动商户数","活动商户数人均","累计活动商户交易额","未参与商户数", "未参与商户人均", "壕气值","当前参与率"};
        }else{//百团
            cols = new String[]{"agentNo", "agentName", "agentLevel", "agentNode","oneAgentNo", "oneAgentName", "oneSaleName","totalMersStr","totalTransStr",
                    "totalActMersStr", "totalAverageTrans", "totalActTransStr", "totalNoActMers", "totalAverageNoActTrans", "score"};
            colsName = new String[]{"代理商编号","代理商名称","代理商级别","代理商节点","一级代理商编号","一级代理商名称","一级代理商所属销售","交易商户数","累计商户交易额",
                    "累计活动商户数","活动商户数人均","累计活动商户交易额","未参与商户数", "未参与商户人均", "牛气值"};
        }
        try {
            ouputStream = response.getOutputStream();
            export.export(cols, colsName, data, response.getOutputStream());
        } catch (Exception e) {
            ExportResult.setExportResult(response,false,"导出异常");
            log.error("导出异常", e);
        } finally {
            try {
                if (ouputStream != null) {
                    ouputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 查询排行版数据
     * 只有数据配置了，就统计榜单
     * @param info
     * @param page
     * @return
     */
    @Override
    public List<AgentActivityData> selectAgentRankingList(AgentActivityData info, Page<AgentActivityData> page,Map<String, Object> msg) {
        List<AgentActivityData>  list=rankingList(info,page,msg);
        return list;
    }

    /**
     * 查询排行数据逻辑
     * @param info
     * @param page 为null 查询全部
     * @return
     */
    private List<AgentActivityData> rankingList(AgentActivityData info, Page<AgentActivityData> page,Map<String, Object> msg){
        Long id=agentActivityDao.checkRankingList(info);
        List<AgentActivityData>  list=new ArrayList<AgentActivityData>();//确保没数据返回时空数组
        if(id==null){
            //实时排名
            //查询配置值
            Map<String,AgentActivityDetail> map=getConfig(info.getActCode());
            //如果没有匹配1的
            AgentActivityDetail config="2".equals(info.getActType())?map.get("config2"):map.get("config1");
            if(config==null){
                msg.put("msg","子活动数据异常");
                msg.put("status", false);
                return null;
            }
            if(0==config.getStatus().intValue()){
                msg.put("msg","活动未开启，暂无数据");
                msg.put("status", false);
                return null;
            }
            if(config.getActiveExt()==null){
                msg.put("msg","活动未设置，暂无数据");
                msg.put("status", false);
                return null;
            }
            if(page!=null){
                list=agentActivityDao.selectAgentRankingList(info,page,config);
            }else{
                list = agentActivityDao.exportAgentRankingListSelect(info,config);
            }
        }else{
            //已生成排行版
            if(page!=null){
                list=agentActivityDao.selectRankingListOld(info,page);
            }else{
                list=agentActivityDao.exportRankingListOld(info);
            }
        }
        msg.put("page",page);
        msg.put("status", true);
        return list;
    }

    /**
     * 导出排行版数据
     * @param info
     * @param response
     * @throws Exception
     */
    @Override
    public void exportAgentRankingList(AgentActivityData info, HttpServletResponse response) throws Exception {
        Map<String, Object> msg=new HashMap<String,Object>();
        List<AgentActivityData>  list=rankingList(info,null,msg);
        //错误转换成导出错误
        if(list==null){
            ExportResult.setExportResult(response,false,msg.get("msg").toString());
            return;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        OutputStream ouputStream = null;
        String fileName = null;
        if("2".equals(info.getActType())){
            fileName = "千团大战榜单" + sdf.format(new Date()) + ".xls";
        }else{
            fileName = "百团大战榜单" + sdf.format(new Date()) + ".xls";
        }
        String fileNameFormat = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        response.setHeader("Content-disposition", "attachment;filename=" + fileNameFormat);
        List<Map<String, String>> data = new ArrayList<Map<String, String>>();

        if(list.size()<1){
            Map<String, String> maps = new HashMap<String, String>();
            maps.put("rankSeq", null);
            maps.put("actName",null);
            maps.put("agentNo",null);
            maps.put("agentName",null);
            maps.put("agentLevel",null);
            maps.put("agentNode",null);
            maps.put("oneAgentNo",null);
            maps.put("oneAgentName",null);
            maps.put("oneSaleName",null);
            maps.put("totalMersStr", null);
            maps.put("totalTransStr", null);
            maps.put("totalActMersStr",null);
            maps.put("totalAverageTrans",null);
            maps.put("totalActTransStr",null);
            maps.put("totalNoActMers",null);
            maps.put("totalAverageNoActTrans",null);
            maps.put("score",null);
            maps.put("rewardStr",null);
            if("2".equals(info.getActType())){
                maps.put("rewardStr", null);
                maps.put("joinRatio",null);
            }
            data.add(maps);
        }else{
            for (AgentActivityData item : list) {
                Map<String, String> maps = new HashMap<>();
                maps.put("rankSeq", item.getRankSeq()==null?null:item.getRankSeq().toString());
                maps.put("agentNo", item.getAgentNo());
                maps.put("agentName", item.getAgentName());
                maps.put("agentLevel", item.getAgentLevel());
                maps.put("agentNode", item.getAgentNode());
                maps.put("oneAgentNo", item.getOneAgentNo());
                maps.put("oneAgentName", item.getOneAgentName());
                maps.put("oneSaleName", item.getOneSaleName());
                maps.put("totalMersStr", item.getTotalMersStr()==null?null:item.getTotalMersStr().toString());
                maps.put("totalTransStr", item.getTotalTransStr()==null?null:item.getTotalTransStr().toString());
                maps.put("totalActMersStr", item.getTotalActMersStr()==null?null:item.getTotalActMersStr().toString());
                maps.put("totalAverageTrans", item.getTotalAverageTrans()==null?null:item.getTotalAverageTrans().toString());
                maps.put("totalActTransStr", item.getTotalActTransStr()==null?null:item.getTotalActTransStr().toString());
                maps.put("totalNoActMers", item.getTotalNoActMers()==null?null:item.getTotalNoActMers().toString());
                maps.put("totalAverageNoActTrans", item.getTotalAverageNoActTrans()==null?null:item.getTotalAverageNoActTrans().toString());
                maps.put("score", item.getScore()==null?null:item.getScore().toString());
                maps.put("rewardStr", item.getRewardStr());
                if("2".equals(info.getActType())){
                    maps.put("rewardConfig", item.getRewardConfig());
                    maps.put("joinRatio", item.getJoinRatio());
                }
                data.add(maps);
            }
        }
        ListDataExcelExport export = new ListDataExcelExport();
        String[] cols=null;
        String[] colsName=null;
        if("2".equals(info.getActType())){//千团
            cols = new String[]{"rankSeq","agentNo", "agentName", "agentLevel", "agentNode","oneAgentNo", "oneAgentName", "oneSaleName","totalMersStr","totalTransStr",
                    "totalActMersStr", "totalAverageTrans", "totalActTransStr", "totalNoActMers", "totalAverageNoActTrans", "score", "rewardConfig", "joinRatio" ,"rewardStr"};
            colsName = new String[]{"排名","代理商编号","代理商名称","代理商级别","代理商节点","一级代理商编号","一级代理商名称","一级代理商所属销售","交易商户数","累计商户交易额",
                    "累计活动商户数","活动商户数人均","累计活动商户交易额","未参与商户数", "未参与商户人均", "壕气值", "牛团悬赏", "当前参与率", "牛团奖励"};
        }else{//百团
            cols = new String[]{"rankSeq","agentNo", "agentName", "agentLevel", "agentNode","oneAgentNo", "oneAgentName", "oneSaleName","totalMersStr","totalTransStr",
                    "totalActMersStr", "totalAverageTrans", "totalActTransStr", "totalNoActMers", "totalAverageNoActTrans", "score", "rewardStr"};
            colsName = new String[]{"排名","代理商编号","代理商名称","代理商级别","代理商节点","一级代理商编号","一级代理商名称","一级代理商所属销售","交易商户数","累计商户交易额",
                    "累计活动商户数","活动商户数人均","累计活动商户交易额","未参与商户数", "未参与商户人均", "牛气值", "牛团奖励"};
        }
        try {
            ouputStream = response.getOutputStream();
            export.export(cols, colsName, data, response.getOutputStream());
        } catch (Exception e) {
            ExportResult.setExportResult(response,false,"导出异常");
            log.error("导出异常", e);
        } finally {
            try {
                if (ouputStream != null) {
                    ouputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
